# == Schema Information
#
# Table name: people
#
#  id            :integer(4)      not null, primary key
#  uid           :string(50)      not null
#  name          :string(60)
#  email         :string(70)
#  photo_url     :string(255)
#  link          :string(255)
#  login         :string(60)
#  gender        :string(10)
#  token         :string(255)
#  answers_count :integer(1)      default(0)
#  created_at    :datetime
#  updated_at    :datetime
#
# Indexes
#
#  index_people_on_uid  (uid)
#

class Person < ActiveRecord::Base
  has_many :answers, :dependent => :destroy
  has_many :questions, :through => :answers
  
  scope :with_name, lambda{|name| where(["#{quoted_table_name}.name LIKE ?", "%#{name}%"])}
  scope :with_ip, lambda{|name| where(["answers.request_ip = ?", name]).includes(:answers)}
  scope :correct, lambda{|count| select('people.id, answers.*, COUNT(answers.id) as answ_count').joins(:answers).where("answers.correct_answer = answers.answer_id").having(["answ_count >= ?", count]).group("people.id")}
  
  class << self
    def app
      FbGraph::Application.new(SiteConfig.fb_app_id, :secret => SiteConfig.fb_app_secret)
    end

    def auth(redirect_uri = nil)
      FbGraph::Auth.new(SiteConfig.fb_app_id, SiteConfig.fb_app_secret, :redirect_uri => redirect_uri)
    end

    def identify(fb_user)
      _fb_user_ = find_or_initialize_by_uid(fb_user.identifier.try(:to_s))
      
      if _fb_user_.new_record?
        fb_user = fb_user.fetch
        _fb_user_.token = fb_user.access_token.access_token
        _fb_user_.name = fb_user.name
        _fb_user_.email = fb_user.email
        _fb_user_.photo_url = profile_img(fb_user.identifier)
        _fb_user_.gender = fb_user.gender
        _fb_user_.login = fb_user.username
        _fb_user_.link = fb_user.link
        
        _fb_user_.save!
      end
     
      _fb_user_
    end
    
    # square | small | normal | large 
    #
    def profile_img(uid, type="normal")
      "http://graph.facebook.com/#{uid}/picture?type=#{type}"
    end
  end
  
  def profile
    @profile ||= FbGraph::User.me(self.token).fetch
  end
  
  def img(type="normal")
    Person.profile_img(self.uid, type)
  end
  
  def profile_link
    "http://www.facebook.com/profile.php?id=#{self.uid}"
  end
end
